package cn.bluedot.framework.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bluedot.framework.core.BeanFactory;
import cn.bluedot.framework.core.ClassScanner;
import cn.bluedot.framework.service.BaseService;
import cn.bluedot.framework.util.WebContext;
import cn.bluedot.framework.util.WebUtils;
import cn.bluedot.framework.util.XMLParser;
import cn.bluedot.framework.web.HandlerManager;
import cn.bluedot.framework.web.RequestHandler;
import cn.bluedot.framework.web.ViewResolver;


public class DispatcherServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
				
		try {
			//1、包扫描
			List<Class<?>> classList = ClassScanner.scanClasses("cn.bluedot.tea");
			//2、类实例化、依赖注入
			BeanFactory.initBean(classList);
			//3、映射处理
			HandlerManager.resolveMappingHandler(classList);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		//解析XML
		XMLParser.getInstance(); 
	}
	
	@Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
		WebContext.request.set(req);
		WebContext.response.set(res);
		
		String uri = WebUtils.getPath(req);
			
		RequestHandler handler = HandlerManager.getHandler(uri); //根据请求uri拿到对应的service方法信息
					
		if(handler == null) {
			res.sendError(404,"The page is not found");
			return;
		}				
		
		Map<String, Object[]> params = WebUtils.getRequestParams(req); //存储传入参数
		
		Map<String, Object> data = new HashMap<>(); //存储返回数据
		
		BaseService.creatService(handler, params, data); //调用对应的业务处理方法
		
		//视图处理器(处理重定向，转发等；处理返回值，如返回JSON数据等)
		Method method = handler.getMethod();
		ViewResolver.execute(method, req, res, data);
		
    }
	
}